package com.eduadmin.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.eduadmin.entity.BaseDataTable;
import com.eduadmin.service.IBaseDataTableService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class BaseDataTableDataUploadListener extends AnalysisEventListener<BaseDataTable> {
    //依赖注入
    private final IBaseDataTableService baseDataTableService;
    public BaseDataTableDataUploadListener(IBaseDataTableService baseDataTableService) {
        this.baseDataTableService = baseDataTableService;
    }

    private static final int BATCH_COUNT = 600;
    List<BaseDataTable> list = new ArrayList<>();

    @Override
    public void invoke(BaseDataTable data, AnalysisContext context) {
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        list.add(data);
        if (list.size() >= BATCH_COUNT) {
            saveData();
            list.clear();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", list.size());
        if (!CollectionUtils.isEmpty(list)) {
            baseDataTableService.addBaseDataTables(list);
        }
        log.info("存储数据库成功！");
    }


}
